﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using Service;
using Entity;
using System.Threading;
using Common;
using System.Diagnostics;
using Winform.Properties;

namespace Winform
{
    public partial class Form_Main : Form
    {
        static List<Company> result = new List<Company>();
        static List<Company> temp = new List<Company>();
        EcanQQ qqfrm = new EcanQQ();
        Thread t;
        public Form_Main()
        {
            InitializeComponent();
            Init();
        }

        #region Init
        private void Init()
        {
            Init_Setting();
            Init_UI();
        }

        private void Init_UI()
        {
            CheckForIllegalCrossThreadCalls = false;
            Bind_City();
        }

        private void Bind_City()
        {
            ddlCity.Items.Clear();
            DataTable dt = DAL.SQLiteHelper.Query("select * from City order by OrderNum");
            List<City> list = Table2Entity_Service.Bin_City(dt);
            foreach (City item in list)
            {
                ddlCity.Items.Add(new CheckBoxItem(item.Name, item));
            }
            ddlCity.SelectedIndex = 0;
            gbTask.Text = "当前选择城市：" + ddlCity.Text;
        }
        //绑定Keyword列表，且列表刷新后保存勾选状态。
        private void Refresh_Keyword()
        {
            //重新绑定前保存当前勾选状态
            bool[] temp = new bool[chbListKeyword.Items.Count];
            for (int i = 0; i < chbListKeyword.Items.Count; i++)
            {
                temp[i] = chbListKeyword.GetItemChecked(i);
            }
            //绑定
            Bind_Keyword();
            //绑定完之后还原勾选状态
            if (chbListKeyword.Items.Count < 1)
            {
                return;
            }
            for (int i = 0; i < temp.Length; i++)
            {
                chbListKeyword.SetItemChecked(i, temp[i]);
            }
        }
        private void Bind_Keyword()
        {
            chbListKeyword.Items.Clear();
            DataTable dt = DAL.SQLiteHelper.Query("select * from Keyword order by OrderNum");
            List<Keyword> list = Table2Entity_Service.Bin_Keyword(dt);
            foreach (Keyword item in list)
            {
                CheckBoxItem i = new CheckBoxItem(item.Name + "|" + item.Page_From.ToString() + " - " + item.Page_To.ToString(), item);
                chbListKeyword.Items.Add(i);
            }
        }
        private void Init_Setting()
        {
            DAL.SQLiteHelper.ConnectionString = @"Data Source=" + Application.StartupPath + @"\db\Jelly.db3;Pooling=true;FailIfMissing=false";
        }
        #endregion

        private void Form_Main_Load(object sender, EventArgs e)
        {
            Bind_Keyword();
        }
        
        private void DoPick()
        {
            List<Task> list = Get_TaskList();
            gbTask.Enabled = false;
            foreach (Task t in list)
            {
                Base_Pick_Service service = new Base_Pick_Service(t, proPick, lblPageIndex);
                try
                {
                    temp = service.Pick();
                }
                catch (Exception ex)
                {
                    DateTime dateTime = DateTime.Now;
                    Common.FileHelper.FileAdd(Application.StartupPath + @"\Exception.log", dateTime.ToString("yyyy-MM-dd HH:mm:ss") + " · " + ex.Message + Environment.NewLine + ex.StackTrace + "================================================================================================");
                }
                result.AddRange(temp);
                //gvResult.DataSource = temp;
            }
            if (list.Count>1)
            {
                //gvResult.DataSource = result;
            }
            EOF();
        }

        private void EOF()
        {
            gbTask.Enabled = true;
            timRefresh.Enabled = false;
            lblPageIndex.Text = "采集完毕！";
            proPick.Value = 0;
            this.btnRun.Image = Resources.play;
            isPlaying = false;
        }

        private List<Task> Get_TaskList()
        {
            List<Task> list = new List<Task>();
            for (int i = 0; i < chbListKeyword.Items.Count; i++)
            {
                if (chbListKeyword.GetItemChecked(i))
                {
                    Task t = new Task();
                    t.City = (ddlCity.SelectedItem as CheckBoxItem).Value as City;
                    t.Keyword = (chbListKeyword.Items[i] as CheckBoxItem).Value as Keyword;
                    list.Add(t);
                }
            }
            return list;
        }
        #region 全选、全部选、反选
        /// 全选
        private void btnSelect_All_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < chbListKeyword.Items.Count; i++)
            {
                chbListKeyword.SetItemChecked(i, true);
            }
        }
        /// 全不选
        private void btnSelect_Null_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < chbListKeyword.Items.Count; i++)
            {
                chbListKeyword.SetItemChecked(i, false);
            }
        }
        //反选
        private void btnSelect_Invert_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < chbListKeyword.Items.Count; i++)
            {
                if (chbListKeyword.GetItemChecked(i))
                {
                    chbListKeyword.SetItemChecked(i, false);
                }
                else
                {
                    chbListKeyword.SetItemChecked(i, true);
                }
            }
        }
        #endregion

        private void chbCity_SelectedIndexChanged(object sender, EventArgs e)
        {
            gbTask.Text = "当前选择城市：" + ddlCity.Text;
        }

        #region Keyword
        /// 添加一个Keyword
        private void btnAdd_Keyword_Click(object sender, EventArgs e)
        {
            if (new Form_Keyword_Operate().ShowDialog() == DialogResult.OK)
            {
                Bind_Keyword();
            }
        }
        //批量删除Keyword
        private void btnDel_Keyword_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你断定肯定确定以及一定要删除勾选的任务么？", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }
            for (int i = 0; i < chbListKeyword.Items.Count; i++)
            {
                if (chbListKeyword.GetItemChecked(i))
                {
                    string name = ((chbListKeyword.Items[i] as CheckBoxItem).Value as Keyword).Name;
                    DAL.DAL_Service.Keyword_Del(name);
                }
            }
            Refresh_Keyword();
        }
        //编辑Keyword
        private void chbListKeyword_DoubleClick(object sender, EventArgs e)
        {
            if (chbListKeyword.SelectedItem != null)
            {
                Form_Keyword_Operate form = new Form_Keyword_Operate((chbListKeyword.SelectedItem as CheckBoxItem).Value as Keyword);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Refresh_Keyword();
                }
            }
        }
        //鼠标对Keyword列表控件操作的优化
        private void chbListKeyword_MouseDown(object sender, MouseEventArgs e)
        {
            if (chbListKeyword.Items.Count < 1)
            {
                return;
            }
            int index = e.Y / chbListKeyword.GetItemHeight(0);
            //如果列表中的项少于计算出来的index
            if (chbListKeyword.Items.Count <= index)
            {
                return;
            }
            chbListKeyword.SelectedIndex = index;
            if (e.Button == MouseButtons.Left)//左键
            {
                if (chbListKeyword.GetItemChecked(index))
                {
                    chbListKeyword.SetItemChecked(index, false);
                }
                else
                {
                    chbListKeyword.SetItemChecked(index, true);
                }
            }
        }
        #endregion

        //刷新关键字列表
        private void timRefresh_Tick(object sender, EventArgs e)
        {
            Refresh_Keyword();
        }
        //窗口磁性吸附
        private void timEcanQQ_Tick(object sender, EventArgs e)
        {
            int height = this.Height;
            qqfrm.hide_show(this, ref height, timEcanQQ);
        }

        /// <summary>
        /// 打开导出文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFolder_Click(object sender, EventArgs e)
        {
            Process.Start(Application.StartupPath + @"\Excels");
        }
        bool isPlaying = false;
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (isPlaying)
            {
                t.Abort();
                EOF();
            }
            else
            {
                if (Get_TaskList().Count < 1)
                {
                    MessageBox.Show("当前未勾选任何任务，请添加或勾选任务后开始采集。", "无可执行的任务", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                this.btnRun.Image = Resources.stop;
                timRefresh.Enabled = true;
                isPlaying = true;
                t = new Thread(DoPick);
                t.Start();
            }
        }

        #region 导出到Excel
        private void btnExport_All_Click(object sender, EventArgs e)
        {
            DataTable dt = DAL.SQLiteHelper.Query("select * from Company");
            List<DataTable> dtList = new List<DataTable>();
            dtList.Add(dt);
            string title = "❤Jelly-所有客户";
            new Common.ExcelHelper().Export(dtList, title, Application.StartupPath + @"\Excels\" + title + ".xls");
            MessageBox.Show("导出成功！");
        }
        private void btnExport_All_Date_Click(object sender, EventArgs e)
        {
            DataTable dateDt = DAL.SQLiteHelper.Query("select date(InsTime) from Company group by date(InsTime)");
            List<DataTable> dtList = new List<DataTable>();
            foreach (DataRow dr in dateDt.Rows)
            {
                DataTable dt = DAL.SQLiteHelper.Query("select * from Company where strftime('%j',InsTime)=strftime('%j','" + dr[0].ToString() + "')");
                dt.TableName = dr[0].ToString();
                dtList.Add(dt);
            }
            string title = "❤Jelly-所有客户-日期分组";
            new Common.ExcelHelper().Export(dtList, title, Application.StartupPath + @"\Excels\" + title + ".xls");
            MessageBox.Show("导出成功！");
        }

        private void btnExport_All_Key_Click(object sender, EventArgs e)
        {
            DataTable dateDt = DAL.SQLiteHelper.Query("select Keyword from Company group by Keyword");
            List<DataTable> dtList = new List<DataTable>();
            foreach (DataRow dr in dateDt.Rows)
            {
                DataTable dt = DAL.SQLiteHelper.Query("select * from Company where Keyword = '" + dr[0].ToString() + "'");
                dt.TableName = dr[0].ToString();
                dtList.Add(dt);
            }
            string title = "❤Jelly-所有客户-关键字分组";
            new Common.ExcelHelper().Export(dtList, title, Application.StartupPath + @"\Excels\" + title + ".xls");
            MessageBox.Show("导出成功！");
        }
        //-------------------------------------------------------------------------------------------------------------------------
        private void btnExport_Today_Click(object sender, EventArgs e)
        {
            List<DataTable> dtList = new List<DataTable>();
            DataTable dt = DAL.SQLiteHelper.Query("select * from Company where strftime('%j',InsTime)=strftime('%j','now')");
            dt.TableName = DateTime.Now.ToString("yyyy-MM-dd");
            dtList.Add(dt);
            string title = "❤Jelly-" + DateTime.Now.ToString("yyyy-MM-dd");
            new Common.ExcelHelper().Export(dtList, title, Application.StartupPath + @"\Excels\" + title + ".xls");
            MessageBox.Show("导出成功！");
        }

        private void btnExport_Today_Key_Click(object sender, EventArgs e)
        {
            DataTable dateDt = DAL.SQLiteHelper.Query("select Keyword from Company group by Keyword");
            List<DataTable> dtList = new List<DataTable>();
            foreach (DataRow dr in dateDt.Rows)
            {
                DataTable dt = DAL.SQLiteHelper.Query("select * from Company where strftime('%j',InsTime)=strftime('%j','now') and Keyword = '" + dr[0].ToString() + "'");
                dt.TableName = dr[0].ToString();
                dtList.Add(dt);
            }
            string title = "❤Jelly-" + DateTime.Now.ToString("yyyy-MM-dd") + "-关键字分组";
            new Common.ExcelHelper().Export(dtList, title, Application.StartupPath + @"\Excels\" + title + ".xls");
            MessageBox.Show("导出成功！");
        }
        #endregion

        private void btnExport_ButtonClick(object sender, EventArgs e)
        {
            btnExport.ShowDropDown();
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            new Form_About().ShowDialog();
        }
    }
}
